package com.example.demo5;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端
 */
public class Client {
    private Scanner sc = new Scanner(System.in);
    private Socket socket;

    public static void main(String[] args) {
        try {
            Client client = new Client();
            client.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void start() throws Exception {
        socket = new Socket("127.0.0.1", 8888);
        System.out.println("连接服务端成功！");
        // 1.开发界面
        while (true) {
            System.out.println("1.登录");
            System.out.println("2.注册");
            System.out.print("请您输入你的选择(输入exit退出)：");
            String msg = sc.nextLine();
            if ("exit".equals(msg)) {
                System.out.println("欢迎下次光临！");
                socket.close();
                return;
            }
            switch (msg) {
                case "1":
                    login();
                    break;
                case "2":
                    register();
                    break;
                default:
                    System.out.println("没有该操作~~");
            }
        }
    }

    public void login() throws Exception {
        System.out.println("--------登录操作--------");
        System.out.println("请输入登录信息：");
        System.out.println("登录名称：");
        String loginName = sc.nextLine();

        System.out.println("登录密码：");
        String passWord = sc.nextLine();

        // 2.发送登录名称和密码到服务端保存
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeInt(2); // 2代表登录
        dos.writeUTF(loginName);
        dos.writeUTF(passWord);
        dos.flush();

        // 3.接收服务端返回的结果
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        System.out.println(dis.readUTF());
    }

    public void register() throws Exception {
        System.out.println("--------注册操作--------");
        System.out.println("请输入注册信息：");
        // 1.提示用户输入的用户名和密码
        System.out.print("请您输入用户名：");
        String loginName = sc.nextLine();

        System.out.print("请您输入密码：");
        String passWord = sc.nextLine();

        // 2.发送登录名称和密码到服务端保存
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeInt(1); // 1代表注册
        dos.writeUTF(loginName);
        dos.writeUTF(passWord);
        dos.flush();

        // 3.接收服务端返回的结果
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        System.out.println(dis.readUTF());
    }
}
